package ma.myschool.app.dao.hibernate;

import java.util.List;

import ma.myschool.app.dao.EleveDao;
import ma.myschool.app.model.Eleve;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;


/**
 * This class interacts with hibernate session to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
 * @author jgarcia (updated to hibernate 4)
 */
@Repository
public class EleveDaoHibernate extends GenericDaoHibernate<Eleve, Long> implements EleveDao {

    /**
     * Constructor to create a Generics-based version using Role as the entity
     */
    public EleveDaoHibernate() {
        super(Eleve.class);
    }

    @Override
    public List<Eleve> getAll(){
    	return getSession().createQuery("FROM Eleve e WHERE e.deleted=false").list();
    }
    
	@Override
	public List<Eleve> searchCustom(Eleve eleve) {
		StringBuilder query = new StringBuilder("from Eleve e WHERE e.deleted=false ");
		
		if(eleve.getGroupe() != null && eleve.getGroupe().getId() != null && eleve.getGroupe().getId() > 0)
			query.append(" AND e.groupe.id=" + eleve.getGroupe().getId());
		if(StringUtils.isNotEmpty(eleve.getNumeroInscription()))
			query.append(" AND e.numeroInscription='" + eleve.getNumeroInscription() + "'");
		if(StringUtils.isNotEmpty(eleve.getNom()))
			query.append(" AND e.nom LIKE '%" + eleve.getNom() + "%'");
		if(StringUtils.isNotEmpty(eleve.getPrenom()))
			query.append(" AND e.prenom LIKE '%" + eleve.getPrenom() + "%'");
		
		return getSession().createQuery(query.toString()).list();
	}

	@Override
	public Eleve loadEleveByNumeroInscription(String numeroInscription) {
		List eleves = getSession().createQuery("FROM Eleve e WHERE e.deleted=false AND e.numeroInscription='" + numeroInscription + "'").list();
        if (eleves.isEmpty()) {
            return null;
        } else {
            return (Eleve) eleves.get(0);
        }
	}

	@Override
	public void deleteEleve(Long id) {
		getSession().createQuery("UPDATE Eleve e SET e.deleted=true WHERE e.id=" + id).executeUpdate();
	}

	@Override
	public List<Eleve> getListEleveRetardPay() {
		StringBuilder query = new StringBuilder("FROM Paiement p WHERE p.eleve.deleted=false AND e.exonere=false");
		query.append(" AND p.reste > 0 ");
		query.append(" OR count(SELECT mp.libelle FROM MoisPaye mp WHERE mp.libelle = p.moisPaye.libelle)  = 0");
		
		return null;
	}

	@Override
	public Number getSizeAll() {
		Number n = (Number) getSession().createQuery("SELECT count(e.id) FROM Eleve e WHERE e.deleted=false AND e.exonere=false").uniqueResult();
		if(n == null)
			n = 0;
		
		return n;
	}

	@Override
	public List<Eleve> getAllWithoutExonere() {
		return getSession().createQuery("FROM Eleve e WHERE e.deleted=false AND e.exonere=false").list();
	}
}
